from PySide2 import QtGui, QtCore, QtWidgets
from PySide2.QtWidgets import *
from PySide2.QtGui import *
from PySide2.QtCore import *
import sys
import random


class Demo(QWidget):
    def __init__(self, parent=None):
        super(Demo, self).__init__(parent)
        self.setWindowTitle('绘制验证码')
        self.resize(150, 60)
    char = []
    for i in range(48, 58):
        char.append(chr(i))      # 添加0~9的数字
    for i in range(65, 91):
        char.append(chr(i))       # 添加A~Z的大写字母
    for i in range(97, 123):
        char.append(chr(i))        # 添加a~z的小写字母
    # 生成随机数字或者字母

    def rndChar(self):
        return self.char[random.randint(0, len(self.char))]

    def paintEvent(self, event):
        painter = QPainter(self)
        painter.drawRect(10, 10, 100, 30)
        painter.setPen(Qt.red)
        # 绘制干扰线（此处设置20条干扰线，可以随意设置）
        for i in range(20):
            painter.drawLine(
                random.randint(10, 110), random.randint(10, 40),
                random.randint(10, 110), random.randint(10, 40)
            )
            painter.setPen(Qt.green)
        # 绘制噪声点（此处设置500个噪声点，可以随意设置）
        for i in range(500):
            painter.drawPoint(random.randint(10, 110), random.randint(10, 40))
        painter.setPen(Qt.black)
        font = QFont()
        font.setFamily('楷体')
        font.setPointSize(15)
        font.setBold(True)
        font.setUnderline(True)
        painter.setFont(font)
        for i in range(4):
            painter.drawText(30 * i + 10, 30, str(self.rndChar()))


if __name__ == '__main__':
    app = QApplication(sys.argv)
    demo = Demo()
    demo.show()
    sys.exit(app.exec_())




